package com.leiyuee.io.BIO;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 说明：
 * 使用BIO编写一个服务器端，监听6666端口，当有客户端连接时，就启动一个线程与之通讯
 * 
 * @author Yu_Lei
 * @date 2024/7/11
 */
public class BIOServer {
    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动，监听端口6666");
        
        while (true) {
            System.out.println("线程信息id " + Thread.currentThread().getId() + "名字 ="+Thread.currentThread().getName());
            System.out.println("等待客户端连接...");
            Socket accept = serverSocket.accept();
            System.out.println("客户端连接成功，线程信息id " + Thread.currentThread().getId() + "名字 ="+Thread.currentThread().getName());
            //创建一个线程，与之通信
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    handler(accept);
                }
            });
        }
    }

    private static void handler(Socket socket) {
        try {
            System.out.println("线程信息id = " + Thread.currentThread().getId() + "名字 = " + Thread.currentThread().getName());
            byte[] bytes = new byte[1024];
            //通过socket获取输入流
            InputStream inputStream = socket.getInputStream();
            //循环的读取客户端发送的数据
            while (true) {
                System.out.println("线程信息id = " + Thread.currentThread().getId() + "名字 = " + Thread.currentThread().getName());
                System.out.println("read....");
                int read = inputStream.read(bytes);
                if (read != -1) {
                    System.out.println(new String(bytes, 0, read));//输出客户端发送的数据
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭和client的连接");
            try {
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
